package com.yanqu.road.server.task;

import com.yanqu.road.server.command.CommandControl;
import com.yanqu.road.server.manger.CommandStatisticsMgr;
import com.yanqu.road.message.YanQuMessage;
import com.yanqu.road.server.command.Command;
import io.netty.channel.ChannelHandlerContext;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

public class CrossCommandTask implements Runnable {
	private static Logger logger = LogManager.getLogger(CrossCommandTask.class.getName());
	private static Logger cmdLogger = LogManager.getLogger("COMMAND_TIME");
	private ChannelHandlerContext ctx;

	private YanQuMessage yanQuMessage;
	private long receiveTime;

	public CrossCommandTask(ChannelHandlerContext ctx, YanQuMessage yanQuMessage) {
		this.ctx = ctx;
		this.yanQuMessage = yanQuMessage;
		this.receiveTime = System.nanoTime();
	}

	@Override
	public final void run() {
		long beginTime = System.nanoTime();
		Command cmd = null;
		try {
			cmd = CommandControl.getCommand(yanQuMessage.getCode());
			if (cmd != null) {
				cmd.execute(ctx, yanQuMessage);
			}
		} catch (Exception e) {
			logger.error("execute command error ,message : {}" , yanQuMessage, e);
		} finally {
			long now = System.nanoTime();
			long costTime = now - receiveTime;
			long executeTime = now - beginTime;
			if (costTime > 1000 * 1000000L || executeTime > 100 * 1000000L) {
                String className = "";
                if (cmd != null) {
                    className = cmd.getClass().getSimpleName();
                }
				cmdLogger.debug("command total cost time {} Millis,executeTime {} Mills, userId {}, protocol Num:{} class:{}  ", costTime,executeTime,
						yanQuMessage.getPlayerId(), yanQuMessage.getCode(),className);
			}
			CommandStatisticsMgr.addCommandData(yanQuMessage.getCode(),executeTime);
		}
	}
}
